import os
from itertools import zip_longest
from mutagen.mp3 import MP3
from mutagen.easyid3 import EasyID3



code = "utf_8_sig"
#mod文件所在路径
modpath = r'D:\\Documents\\Paradox Interactive\\Crusader Kings III\\mod\\character\\'
mod_prefix = "MyGO_"
#是否用专辑序号编辑文件夹内容
readtacknum = True
#私货时间，根据自己的情况改
#是否是带有人声的歌曲
is_song = True
# 次级文件夹路径，置空则不分子文件夹
dir = "MyGO_6th_single"
groupname = dir
musicpath = "music\\in_game"
musicplayerpath= "music\\music_player_categories"
localizations = "localization\\simp_chinese"
#下述为操作
def get_tracknum(currentpath,file) -> int:
    audio = MP3(os.path.join(currentpath,file),ID3=EasyID3)
    tracknumber = audio ['tracknumber']
    tracknumber = str(tracknumber).replace('[','').replace(']','').replace("'",'')
    tracknumber = int(tracknumber)
    return tracknumber

def main_handler():
    currentpath = os.path.join(modpath,musicpath,dir)
    music = open(os.path.join(modpath,musicpath, mod_prefix+"music.txt"),"+a", encoding=code)
    musicplayer = open(os.path.join(modpath,musicplayerpath, mod_prefix+dir+"_music_categories.txt"),"w+", encoding=code)
    musicloc = open(os.path.join(modpath,localizations,mod_prefix+"music_l_simp_chinese.yml"),"+a",encoding=code)
    musiclist = os.listdir(currentpath)
    tracknumber = 0
    if is_song == True:
        music.write('''group_'''+groupname+''' = {
\tpause_factor = 20
\tmood = yes
\tcalls = 5
\ttrigger_prio_override = yes
\tis_valid = { 
\t\tOR = {
\t\t\thas_game_rule = allow_random_song
\t\t} 
\t}
}

''')
    else:
        music.write('''group_'''+groupname+''' = {
\tpause_factor = 20
\tcan_be_interrupted = yes
\tmood = yes
\tcalls = 5
\ttrigger_prio_override = yes
\tis_valid = { 
\t\tOR = {
\t\t\thas_game_rule = allow_random_ost
\t\t\thas_game_rule = allow_random_song
\t\t} 
\t}
}

''')
    if readtacknum == True:
        musiclist = sorted(musiclist,key=lambda file: get_tracknum(currentpath,file))
    for file in musiclist:
        if os.path.isfile(os.path.join(currentpath, file)):
            if file[-4:] == '.mp3':
                if readtacknum == True:
                    audio = MP3(os.path.join(currentpath,file),ID3=EasyID3)
                    tracknumber = audio ['tracknumber']
                    tracknumber = str(tracknumber).replace('[','').replace(']','').replace("'",'')
                else:
                    tracknumber = tracknumber +1
                name = groupname+"_"+str(tracknumber)
                music.write(''''''+name+''' = {
\tmusic = "file:/music/in_game/'''+dir+'''/'''+file+'''"
\tname = "'''+name+'''"
\tgroup = group_'''+groupname+'''
}

''')
                musicplayer.write('''\t\t"'''+name+'''"\n''')
                musicloc.write('''
  '''+name+''': "'''+file.split(" - ")[-1].replace('.mp3','')+'''" ''')
main_handler()